package com.cxl.price.action.price;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;

import net.sf.json.JSONArray;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import com.cxl.price.bean.TaoBaoGood;
import com.cxl.price.service.TaoBaoGoodService;
import com.cxl.price.top.service.TopBaseService;
import com.cxl.price.top.service.TopItemCatAndPopsService;
import com.cxl.price.top.service.TopItemResponseService;
import com.cxl.price.top.service.TopProductService;
import com.cxl.price.util.ImageUtil;
import com.cxl.price.util.JsonBinder;
import com.summer.core.action.BaseAction;
import com.taobao.api.ApiException;
import com.taobao.api.FileItem;
import com.taobao.api.domain.Item;
import com.taobao.api.domain.ItemProp;
import com.taobao.api.domain.Product;
import com.taobao.api.domain.PropValue;
import com.taobao.api.request.ItemAddRequest;
import com.taobao.api.request.ItempropsGetRequest;
import com.taobao.api.request.ProductGetRequest;
import com.taobao.api.response.ItemAddResponse;
import com.taobao.api.response.ItempropsGetResponse;
import com.taobao.api.response.ProductGetResponse;

/**
 * @about: 淘宝商品 action
 * @author: wwwlike
 * @create: 2011-07-02
 */
 
 
@ParentPackage("price")			
public class TaoBaoGoodAction extends BaseAction<TaoBaoGood, TaoBaoGoodService> {

	
	private TopItemResponseService topItemResponseService;
	
	@Resource
	public void setTopItemService(TopItemResponseService topItemResponseService) {
		this.topItemResponseService = topItemResponseService;
	}
	
	public void setTaoBaoGood(TaoBaoGood taoBaoGood) {
		setBean(taoBaoGood);
	}

	public TaoBaoGood getTaoBaoGood() {
		return getBean();
	}

	@Resource
	public void setService(TaoBaoGoodService service) {
		this.service = service;
	}

	

	
	public String exportCsv()throws Exception {
		
		List<TaoBaoGood> list=new ArrayList<TaoBaoGood>();
		if(ids==null){
			list=service.getAll();
		}
		else{
			for(String id:ids)
			{
				list.add(service.get(id));
			}
		}
   //头部
		 

   String data = "宝贝名称,宝贝类目,店铺类目,新旧程度,省,城市,出售方式,宝贝价格,加价幅度,宝贝数量,有效期,运费承担,平邮,EMS,快递,付款方式,支付宝,发票,保修,自动重发,放入仓库,橱窗推荐,开始时间,心情故事,宝贝描述,宝贝图片,宝贝属性,团购价,最小团购件数,邮费模版ID,会员打折,修改时间,上传状态,图片状态,返点比例,新图片,视频,销售属性组合,用户输入ID串,用户输入名-值对,商家编码,销售属性别名,代充类型,宝贝编号,数字ID\n";
   //具体的数据,可以动态的从数据库中读取
   ImageUtil image=new ImageUtil();
  
   for(TaoBaoGood bean:list)
   {
	   String description="";
	 if(StringUtils.isNotEmpty(bean.getDescription()))
	 {
		 description =bean.getDescription().replace(",","\\\""+","+"\\\"").replace("\\r","").replace("<br />","");
	 }
	 
	   String shuiying=bean.getVedios();
		
		String imgs[]=bean.getPic().split(";");
		String imageStr="";
		int i=0;
		for(String img:imgs)
		{
			if(i>4)
				break;
			
			String pciTbiStr=RandomStringUtils.random(20,true,true);
			imageStr+=pciTbiStr+":0:"+i+":|;";
			image.saveOtherImgToTbi(img,pciTbiStr);
			if(i==0)
			{
				//第一张图片进行处理
			if(!"0".equals(shuiying)&&!"-1".equals(shuiying))
			{
				//指定水印
			 image.pressImage(shuiying+".png", pciTbiStr+".tbi", 1, 0.8f);
			}
			else if("-1".equals(shuiying))
			{
				int num = new Random().nextInt(3);
				image.pressImage(num+".png", pciTbiStr+".tbi", 1, 0.8f);
			}
			image.addBorderToImage(pciTbiStr+".tbi");
			}
			i++;
		
		}
			if(description.length()>25000)
		   {
		   	description="取得宝贝描述数据超过25000个字符最大长度，请自行去"+bean.getFromUrl()+"提取数据";
		   };
	  data += bean.getTitle()+","+bean.getCategory()+",,0,湖北,武汉,b,"+(Double.parseDouble(bean.getPrice()))+",0,100,7,"+("0".equals(bean.getPostId())?"2":"1")+",0,0,0,,,1,0,0,0,0,2011-6-13  20:47:36,,"+description+",,"+bean.getPopvalue()+",,,"+bean.getPostId()+",1,2011-6-13  20:47:36,,,,"+imageStr+",,,,,,,,,\n"; 
   }

   StringBuilder str = new StringBuilder();
   str.append(data);
   getResponse().setContentType("text/csv");
   getResponse().setCharacterEncoding("gb18030");
   getResponse()
     .setHeader("Content-Disposition",
       "attachment; filename=\""
         + new String("图片.csv".getBytes("gb18030"),
           "iso8859-1") + "\"");
   PrintWriter out = getResponse().getWriter();
   out.write(str.toString());
   out.flush();
   out.close();
   return null;
}
	
	
	/**
	 * 上货到淘宝
	 * @return
	 * @throws ParseException 
	 * @throws ApiException 
	 */
	public String gotoTaobao() throws ApiException, ParseException
	{
		redirectionUrl ="tao_bao_good!list.action";
		try
		{
		if(ids!=null)
		{
			for(String id:ids)
			{
				TaoBaoGood good=service.get(id);
				ItemAddRequest request=new ItemAddRequest();
				request.setTitle(good.getTitle());
				//request.setPrice(good.getPrice());
				//request.setDesc(good.getDescription());
				request.setPrice("1000");
				request.setDesc("描述描述描述描述描述描述");
				request.setCid(Long.parseLong(good.getCategory()));
				request.setProps(good.getPopvalue());
				request.setSellerCids(good.getShopCategoryId());
				request.setPostageId(Long.parseLong(good.getPostId()));
				if(!"0".equals(good.getPostId()))
				{
					request.setFreightPayer("buyer");
				}
				byte[] kk=ImageUtil.getHttpImgBytes(good.getPic());
				FileItem fItem = new FileItem(new ImageUtil().getImageFile(good.getNewPic()));
				request.setImage(fItem);
				
				//request.setSellerCids("1101,1102,1103"); // 可选 商品所属的店铺类目列表。按逗号分隔。结构:",cid1,cid2,...,"，如果店铺类目存在二级类目，必须传入子类目cids。
				ItemAddResponse response=topItemResponseService.getItemAddResponse(request,getRequest());
				Item item=response.getItem();
				//System.out.println(response.getMsg());
				
				if(response.getMsg()!=null)
				{
					return ERROR;
				}
				if(item!=null&&item.getNumIid()!=null)
				service.delete(id);
			
			}
		}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
			return ERROR;
		}
		
		return SUCCESS;
	}
	
	public String popSelect()
	{
		System.out.println(getParameter("path"));
	
		List<Map<String, String>> optionList = new ArrayList<Map<String, String>>();
	
			Map<String, String> map = new HashMap<String, String>();
			map.put("title", "222");
			map.put("value", "333");
			optionList.add(map);
			map = new HashMap<String, String>();
			map.put("title", "444");
			map.put("value", "333333");
			optionList.add(map);
	
		JSONArray jsonArray = JSONArray.fromObject(optionList);
		return ajaxJson(jsonArray.toString());
	}

	
//	public String getProps()
//	{
//		String cid=getParameter("cid");
//		String pidvid=getParameter("pidvid");
//		
//	}
	
	public String getPop() throws ApiException, IOException
	{
	//	System.out.println(getParameter("popValue"));
		TopItemCatAndPopsService servicetic=new TopItemCatAndPopsService();
		ItempropsGetRequest request=new ItempropsGetRequest();
		request.setCid(Long.parseLong(getParameter("cid")));
		//request.setIsKeyProp(true);
		String child_path=getParameter("child_path");
		if("0".equals(child_path))
		{
			return null;
		}
		String bind=getParameter("bind");
	//	System.out.println("---------"+child_path);
		if(child_path!=null)
		{
			request.setChildPath(child_path);
		}
		else if(bind!=null)
		{
			request.setChildPath(bind);
		}
		
		ItempropsGetResponse response=servicetic.getItempropsGetResponse(request);
		
		List<ItemProp> pp= response.getItemProps();
		if(bind!=null&&pp==null)
		{
			return null;
		}
		
		
		Map<String, Object> map=new HashMap<String, Object>();
		//if 根据属性去一级一级往下查  else 查到查不到为止 就去产品里面去查 非关键属性。 非关键属性 有可能没有 那么 就又需要 去 属性里面去手工提取出来   
		if(pp!=null)
		{
		for(ItemProp p:pp)
		{
			if(p.getMust()&&p.getIsKeyProp())
			{
				//查找 必须的关键属性
				Long pid=p.getPid();
				String name=p.getName();
				
				if(StringUtils.isNotEmpty(child_path))
				{
					String pidvid[]=child_path.split(";");
					String pidPath="";
					for(String a:pidvid)
					{
						pidPath+=a.split(":")[0]+" ";
					}
				map.put("selectClass",pidPath+pid);
				}
				else
				{
					map.put("selectClass",pid);
				}
				
				map.put("pid",pid);
				map.put("keyProp", true);
				map.put("name", name);
				map.put("parent_path", child_path==null?"":child_path);
				List<PropValue> popValue=p.getPropValues();
				map.put("pop", popValue);
					  JSONArray jsonObject = JSONArray.fromObject(map);
		        String content=jsonObject.toString();
				return ajaxJson(content);
			
			
				
			}
		 }
		}
		else
		{
			
			TopProductService productServcie=new TopProductService();
			ProductGetRequest ee=new ProductGetRequest();
			ee.setCid(Long.parseLong(getParameter("cid")));
			ee.setFields("product_id,cid,cat_name,props,props_str,name,binds,binds_str,sale_props,sale_props_str,price,desc,pic_url,created,modified,product_img.id,product_img.url,product_img.position,product_prop_img.id,product_prop_img.props,product_prop_img.url,product_prop_img.position");
			ee.setProps(child_path);
			ProductGetResponse re=productServcie.getProductGetResponse(ee);
			Product product=re.getProduct();
			if(product!=null)
			{
			//查询到该产品的非关键属性  匹配到 非关键属性 
			map.put("binds", product.getBinds());
			map.put("binds_str",product.getBindsStr());
			map.put("props_str", product.getPropsStr());
			//map.put("desc", product.getDesc());
			map.put("product_id",product.getProductId());
			map.put("parent_path", child_path);
			  JSONArray jsonObject = JSONArray.fromObject(map);
		        String content=jsonObject.toString();
				return ajaxJson(content);
			}
			else
			{
				//没有查询到该产品的关键属性，但是非关键属性 有可能 有必填项目
				 request=new ItempropsGetRequest();
				request.setCid(Long.parseLong(getParameter("cid")));
				request.setIsKeyProp(false);//查找非关键属性
				request.setChildPath(bind);
				 response=servicetic.getItempropsGetResponse(request);
				 
				  pp= response.getItemProps();
					
					if(pp!=null)
					{
						List<Map> mylist=new ArrayList<Map>();
					for(ItemProp p:pp)
					{
						if(p.getMust())
						{
							 map=new HashMap<String, Object>();
							Long pid=p.getPid();
							String name=p.getName();
							if(StringUtils.isNotEmpty(child_path))
							{
								String pidvid[]=child_path.split(";");
								String pidPath="";
								for(String a:pidvid)
								{
									pidPath+=a.split(":")[0]+" ";
								}
							map.put("selectClass",pidPath+pid);
							}
							else
							{
								map.put("selectClass",pid);
							}
							map.put("keyProp", false);
							map.put("pid",pid);
							map.put("parent_path", child_path);
							map.put("name", name);
						//	map.put("bind",child_path);
							List<PropValue> popValue=p.getPropValues();
							map.put("pop", popValue);
							mylist.add(map);
							
						}
					 }
					
					  JSONArray jsonObject = JSONArray.fromObject(mylist);
				        String content=jsonObject.toString();
						return ajaxJson(content);
					}
				 
				
				
			}
		}
		
		
		
//	    PrintWriter out = getResponse().getWriter();
//
//	    System.out.println(map.toString());
//        out.print(map.toString());
//
//        out.flush();
//
      return null;


		
//		JSONArray jsonArray = jsonm
//		return ajaxJson(jsonArray.toString());
		
		
	}

	
	public static void main(String[] args) throws ApiException {
		
	
		ItempropsGetRequest req=new ItempropsGetRequest();
		req.setFields("pid,name,must,multi,prop_values");
		req.setCid(350301L);
		ItempropsGetResponse response = new TopBaseService().getTaobaoClient().execute(req);
		JsonBinder gson = new JsonBinder();
//		String abc=gson.toJson(response.getItemProps());
//
//		List<Class<ItemProp>> a; 
//
//		List<ItemProp> list = gson.fromJson(abc,a);
//
//		for(ItemProp prop:list){
//			System.out.println(prop.getName());
//		}
		System.out.println(gson.toJson(response.getItemProps().get(0)));
		//System.out.println(response.getBody());
		ItempropsGetResponse response1=gson.fromJson(gson.toJson(response), response.getClass());
		System.out.println(gson.toJson(response1));
		
	}
	

}
